﻿namespace Mockingbird.MVC.Infrastructure.Authorization
{
    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using Core.Infrastructure.Membership.Identity.Interface;
    using Utilities.Session;


    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public sealed class UserAuthorizeAttribute : AuthorizeAttribute 
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            bool shouldLogIn = true;

            var user = (ICustomPrincipal)HttpContext.Current.Session[SessionConstants.User];

            if(user != null)
            {
                HttpContext.Current.User = user;
                shouldLogIn = false;
            }

            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true);
            if (!skipAuthorization)
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                ////To prevent: "This webpage has a redirect loop" message on login page.
                shouldLogIn = false;
            }

            if (shouldLogIn)
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "LogIn");
                redirectTargetDictionary.Add("controller", "Account");

                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
            }
        }
    }
}